﻿@using System.Web
@using System.Web.Security
@using KSSModel
@inherits umbraco.MacroEngines.DynamicNodeContext

@helper LoginForm()
{
    <div class="loginwrapper">
        <div class="loginwrap zindex100 animate2 bounceInDown">
            <h1 class="logintitle"><span class="iconfa-lock"></span>Sign In <span class="subtitle">Login เพื่อเข้าใช้งานระบบ KSS Online </span></h1>
            <div class="loginwrapperinner">

                <form id="loginform" method="post">
                    <p class="animate4 bounceIn">
                         <label  for="username" style="color: #FFFFFF">รหัสพนักงาน</label>
                        <input type="text" id="username" name="username" placeholder="รหัสพนักงาน" value="@HttpContext.Current.Request.LogonUserIdentity.Name" />
                    </p>
                    <p class="animate5 bounceIn">
                         <label  for="password" style="color: #FFFFFF">Password</label>
                        <input type="password" id="password" name="password" placeholder="Password" />
                    </p>
                    <p class="animate6 bounceIn">
                        @*<button class="btn btn-default btn-block" type="submit" value="login" >Submit</button>*@
                        <input class="btn btn-default btn-block" type="submit" id="submitLogin" name="submit" value="login" />
                    </p>
                    <p>
                        <div id="logginError" style="color:red; font-size: large; display:none">รหัสพนักงาน หรือ Password ไม่ถูกต้อง</div>
                    </p>
                    <p  class="animate7 fadeIn"><a onclick="showForgotPW();" href="#"><span class="icon-question-sign icon-white"></span>ลืมรหัสผ่าน?</a> <a style="float: right" href="/register.aspx"><span class="icon-question-sign icon-white"></span>ลงทะเบียน</a></p>
                    
                </form>

            </div>
            <!--loginwrapperinner-->
        </div>


        <div class="loginshadow animate3 fadeInUp"></div>
    </div>
}
<!--loginwrapper-->
@helper LogoutForm()
{
    <form method="post">
        <input type="submit" id="submit" name="submit" value="logout" />
    </form>
}
@helper Message(string message)
{
    <script type="text/javascript">
        jQuery(document).ready(function () {
            jQuery('#username').addClass('error');
            jQuery('#password').addClass('error');
            jQuery('#logginError').show();
        });
    </script>
     
}

@helper SelectRole(List<tblRole> roles)
{
    <div class="loginwrapper">
        <div class="loginwrap zindex100 animate2 bounceInDown">
            <h1 class="logintitle"><span class="iconfa-lock"></span>Role Selection <span class="subtitle">กรุณาเลือกระบบที่ต้องการทำงาน</span></h1>
            <div class="loginwrapperinner">

                <form id="roleform" method="post">
                    @{
                        foreach (var item in roles)
                        {
                        <input type="radio" name="role" value="@item.RoleName" />@item.RoleName
                        }
                    }
                    <input type="submit" id="submit" name="submit" value="selectRole" />
                </form>
            </div>
            <!--loginwrapperinner-->
        </div>
        <div class="loginshadow animate3 fadeInUp"></div>
    </div>
}
@functions {
    void RoleRedirect(string RoleName)
    {
        switch (RoleName.ToLower())
        {
            case "admin":
                Response.Redirect("/a1itemmanagement.aspx");
                break;
            case "user":
                Response.Redirect("/form.aspx");
                break;
            default:
                Response.Redirect("/form.aspx");
                break;
        }
    } 
}
@{
       
    
    
    var isSubmitLogin = (IsPost && Request["submit"] == "login");
    var isSubmitLogout = (IsPost && Request["submit"] == "logout");
    var isSubmitRole = (IsPost && Request["submit"] == "selectRole");
    var currentUser =Request.Cookies[FormsAuthentication.FormsCookieName];
    var requestedUrl = Request.Url.PathAndQuery.ToString(); // Model.Url;
    if (Request["ReturnUrl"] != null)
    {
        requestedUrl = Request["ReturnUrl"];
    }
    if (Request["logout"] != null)
    {
        FormsAuthentication.SignOut();
        FormsAuthentication.RedirectToLoginPage();
        return;
    }


    if (currentUser != null)
    {
        if (!isSubmitRole && !isSubmitLogout)
        {
            if (Session["Role"] == null || String.IsNullOrEmpty(Session["Role"].ToString()))
            {
                var user = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                var roles = KSSOnline.Controller.UserHelper.GetRolebyUserName(user);
                if (roles.Count > 1)
                {
                    //@SelectRole(roles) 
                    var maxLevel = roles.Max(obj => obj.RoleLevel);
                    var rolename = roles.Where(obj => obj.RoleLevel == maxLevel).ToList();
                    Session["Role"] = roles[0].RoleName;
                    RoleRedirect(rolename[0].RoleName);
                }
                else if (roles.Count == 1)
                {
                    Session["Role"] = roles[0].RoleName;
                    RoleRedirect(roles[0].RoleName);
                }
                else
                {
                    Session["Role"] = "user";
                    Response.Redirect("/form.aspx");
                }
            }
            else
            {
                RoleRedirect(Session["Role"].ToString());
            }
            //@LogoutForm()
        }
        else if (isSubmitRole)
        {
            if (Request.Form["role"] != null)
            {
                Session["Role"] = Request.Form["role"];
                RoleRedirect(Request.Form["role"].ToString());
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }
    }

    if (currentUser == null)
    {
        if (!isSubmitLogin)
        {
            string username = HttpContext.Current.Request.LogonUserIdentity.Name;
            string usernameAD = username.Substring(username.LastIndexOf(@"\") + 1);
            
            if (!string.IsNullOrEmpty(usernameAD))
            {
                var user = KSSOnline.Controller.UserHelper.ValidateUserAd(usernameAD);
                if (user != null && user.Count > 0)
                {
                    FormsAuthentication.SetAuthCookie(user[0].UserName, true);
                    var roles = KSSOnline.Controller.UserHelper.GetRolebyUserName(user[0].UserName);
                    if (roles.Count > 1)
                    {
                        //@SelectRole(roles)
                        var maxLevel = roles.Max(obj => obj.RoleLevel);
                        var rolename = roles.Where(obj => obj.RoleLevel == maxLevel).ToList();
                        Session["Role"] = roles[0].RoleName;
                        RoleRedirect(rolename[0].RoleName);
                    }
                    else if (roles.Count == 1)
                    {
                        Session["Role"] = roles[0].RoleName;
                        RoleRedirect(roles[0].RoleName);
                    }
                    else
                    {
                        Session["Role"] = "user";
                        Response.Redirect("/form.aspx");
                    }
                }
            }
    @LoginForm()
        }
        else
        {
            string username = Request["username"];
            string password = Request["password"];
            var user = KSSOnline.Controller.UserHelper.ValidateUser(username, password);
            if (user != null && user.Count > 0)
            {
                
                FormsAuthentication.SetAuthCookie(username, true);
                var roles = KSSOnline.Controller.UserHelper.GetRolebyUserName(username);
                if (roles.Count > 1)
                {
    //@SelectRole(roles)
                    var maxLevel = roles.Max(obj => obj.RoleLevel);
                    var rolename = roles.Where(obj => obj.RoleLevel == maxLevel).ToList();
                    Session["Role"] = roles[0].RoleName;
                    RoleRedirect(rolename[0].RoleName);
                }
                else if (roles.Count == 1)
                {
                    Session["Role"] = roles[0].RoleName;
                    RoleRedirect(roles[0].RoleName);
                }
                else
                {
                    Session["Role"] = "user";
                    Response.Redirect("/form.aspx");
                }
                // RedirectFromLoginPage does not work that good within the Umbraco context
                // FormsAuthentication.RedirectFromLoginPage(username, true);




            }
            else
            {
    @Message("Login failed for " + username)
    @LoginForm()
            }
        }
    }
}